/*----------------------------------------------------------------------*/
/* PROGRAM: der_MTO.ado							*/
/*									*/
/* PURPOSE:								*/
/* [*] 	This code derives the MTO([x,]p) function given any functional 	*/
/*	form of the ATO([x,]p) function. It uses Mata,  a special 	*/
/*	language in Stata for manipulating matrices. In our case, the 	*/
/*	most useful feature of Mata is being able to take derivatives 	*/
/*	of polynomials.							*/
/*									*/
/* USE ON:								*/
/* [*] 	This is a procedure that does not use the Stata data set as	*/
/*	input, but rather uses a matrix	specified by the user. See the 	*/
/*	"Inputs" section below on how to specify the input matrix.	*/				
/*									*/
/* INPUTS:								*/
/* [*] 	arg_ATO_matrix:	The matrix containing the polynomial expression */
/*	for ATO([x,]p). This matrix should have one row and M+1 columns,*/
/*	where M is the order of the polynomial. The first term in the	*/
/*	matrix is the intercept, the second the linear term, etc. The 	*/
/*	code will work (efficiently) on any (reasonable) polynomial 	*/
/*	order M.							*/
/*									*/
/* OUTPUTS:								*/
/* [*] 	MTO_matrix: The matrix containing the polynomial expression for */
/*	MTO([x,]p). This matrix should have one row and M+1 columns, 	*/
/*	where M is the order of the polynomial (as dictated by the 	*/
/*	order of ATO([x,]p) -- MTO([x,]p) must be the same order as 	*/
/*	ATO([x,]p). The first term in the matrix is the intercept, the 	*/
/*	second the linear term etc.					*/
/*									*/
/* EXAMPLE CALL TO PROCEDURE:						*/
/*	matrix test = J(1,2,.)						*/
/*									*/
/*	matrix test[1,1] = 10582.29					*/
/*	matrix test[1,2] = -11800.62					*/
/*									*/
/*	der_MTO test							*/
/*----------------------------------------------------------------------*/

capture program drop der_MTO

program der_MTO
	args arg_ATO_matrix
	marksample touse
	
	* Execute in Mata
	mata: calc_MTO("`arg_ATO_matrix'")
		
end

* Define the function for deriving MTO([x,]p) in Mata
mata:
	void calc_MTO(string scalar sc_ATO_name)
	{
		cm = st_matrix(sc_ATO_name)
			
		/* a. Multiply ATO(p) by p*/
			for_der_ATO = polymult(cm, (0, 1))
			
		/* b. Take the derivative of p*ATO(p) with respect to p */
			MTO_matrix = polyderiv(for_der_ATO, 1)
			
		/* c. Export to Stata */
			st_matrix("MTO_matrix", MTO_matrix)
			
	}
end
